﻿using System;

namespace ICalendar
{
    /// <summary>
    /// This value type is used to identify values that contain a precise period of time. 
    /// </summary>
    /// <remarks>
    ///  The data type is defined by the following
    /// notation:
    /// 
    /// period     = period-explicit / period-start
    /// period-explicit = date-time "/" date-time
    /// ; [ISO 8601] complete representation basic format for a period of
    /// ; time consisting of a start and end. The start MUST be before the
    /// ; end.'
    /// 
    /// period-start = date-time "/" dur-value
    /// ; [ISO 8601] complete representation basic format for a period of
    /// ; time consisting of a start and positive duration of time.
    /// </remarks>
    public class Period
    {
        private DateTime startPeriod;
        private object endPeriod;

        /// <summary>
        ///  This is the start of the Period.
        /// </summary>
        public DateTime StartPeriod
        {
            get { return startPeriod; }
            set
            {
                SecUtility.VerifyDurationDateTime(value, "StartPeriod");
                startPeriod = value;
            }
        }

        /// <summary>
        ///  This is the end of the Period.
        /// </summary>
        /// <value>
        //   This must be a DateTime or a Duration Type
        /// </value>        
        public object EndPeriod
        {
            get { return endPeriod; }
            set
            {
                SecUtility.VerifyDurationDateTime(value, "EndPeriod");      
                if (value is DateTime)
                {
                    if ((DateTime)value < StartPeriod)
                    {
                        throw new ArgumentOutOfRangeException("The start must be before the end");
                    }
                }

                endPeriod = value;
            }
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="startPeriod">This is the start of the Period. </param>
        /// <param name="endPeriod"> This is the end of the Period. This must be a DateTime or a Duration Type.</param>

        public Period(DateTime startPeriod, object endPeriod)
        {
            this.StartPeriod = startPeriod;
            this.EndPeriod = endPeriod;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string strEndPeriod = EndPeriod is Duration
                                      ? ((Duration) EndPeriod).ToString()
                                      : ((DateTime) EndPeriod).ToICalendarUniversalTimeString();
            return string.Format("{0}/{1}", StartPeriod.ToICalendarUniversalTimeString(), strEndPeriod);
        }
    }
}
